package com.module.imagelib.activityresult;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class ActivityActivityResultFragment extends Fragment implements IRxActivityResult {

    private static String TAG = "ActivityActivityResultFragment";
    private BehaviorSubject<Intent> mObservable;

    public ActivityActivityResultFragment() {
        mObservable = BehaviorSubject.create();
    }

    /**
     * startActivityForResult需要有父Activity
     * @param activity
     * @return
     */
    public static ActivityActivityResultFragment newInstance(Activity activity) {
        FragmentManager fragmentManager = activity.getFragmentManager();
        ActivityActivityResultFragment activityResultFragment = (ActivityActivityResultFragment) fragmentManager.findFragmentByTag(TAG);
        boolean isNewInstance = activityResultFragment == null;
        if (isNewInstance) {
            activityResultFragment = new ActivityActivityResultFragment();
            fragmentManager
                    .beginTransaction()
                    .add(activityResultFragment, TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return activityResultFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mObservable.onNext(data);
        mObservable.onComplete();
    }

    @Override
    public Observable<Intent> startIntent(Intent intent) {
        startActivityForResult(intent, 1000);
        return mObservable;
    }
}
